package com.splatform.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * Created by sunfeihu on 2017/4/6.
 */
public class StartControl {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/index")
    String index() {
        return "index";
    }

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }


    @PostMapping(value = "/wxh")
    String index(String wxh, Model model) throws IOException {
        Map<String, Object> map = jdbcTemplate.queryForMap(" select count(*) as counts from wx_status where wxh = ? ", new Object[]{
                wxh
        });
        //如果没有这个微信号的话
        if (null == map || (Integer) (map.get("counts")) <= 0) {
            Map<String, Object> map1 = jdbcTemplate.queryForMap(" select count(*) as counts from t_submessage where FParentID = 19 and FName = ? ", wxh);
            //如果系统中有这个号的话
            if (null != map1 && (Integer) (map1.get("counts")) == 1) {
                String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
                //先删除图片
                FileSystemUtils.deleteRecursively(new File(path + File.separator + "rukutemp" + File.separator + wxh + File.separator + "qr.png"));
                String cmd = "python " + path + "/ruku.py " + wxh;
                Runtime.getRuntime().exec(cmd);
                model.addAttribute("wxh", wxh);
                return "ruku";
            } else {
                return "not";
            }
        }
        map = jdbcTemplate.queryForMap(" select * from wx_status where wxh = ? ", new Object[]{
                wxh
        });
        String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        //先删除图片
        FileSystemUtils.deleteRecursively(new File(path + File.separator + "temp" + File.separator + wxh + File.separator + "qr.png"));
        model.addAttribute("obj", map);
        return "wxh";
    }

    @GetMapping("/report")
    String report(HttpServletRequest request, Model model, String wxh, String startDate, String endDate) {
        Map<String, Object> map = null;
        try {
            map = jdbcTemplate.queryForMap(" select * from wx_status where wxh = ? ", new Object[]{
                    wxh
            });
            if (null == map || map.size() <= 0) {
                return "fail";
            }
        } catch (Exception e) {
            return "fail";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String start = simpleDateFormat.format(getBeforeDay(Calendar.getInstance()).getTime()) + " 19:00:00";
        if (null != startDate && !"".equals(startDate)) {
            start = startDate;
        }
        String end = simpleDateFormat.format(Calendar.getInstance().getTime()) + " 09:00:00";
        if (null != endDate && !"".equals(endDate)) {
            end = endDate;
        }
        map = jdbcTemplate.queryForMap(" select isnull(count(*),0) as c from wx_add where wxh = ? and add_date between ? and ? ", new Object[]{
                wxh, start, end
        });
        String sql = "SELECT CONVERT( DATETIME, CASE WHEN datepart(mi, add_date) < 30 THEN CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':00:00' ELSE CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':30:00' END) AS DATE, COUNT(*) AS counts FROM wx_add WHERE wxh = ? AND add_date BETWEEN ? AND ? GROUP BY CONVERT( DATETIME, CASE WHEN datepart(mi, add_date) < 30 THEN CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':00:00' ELSE CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':30:00' END) ORDER BY CONVERT( DATETIME, CASE WHEN datepart(mi, add_date) < 30 THEN CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':00:00' ELSE CONVERT(VARCHAR(100), add_date, 23) + ' ' + datename(hh, add_date) + ':30:00' END) ASC";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{wxh, start, end});
        JSONArray arr = new JSONArray();
        if (null != list && list.size() > 0) {
            JSONObject obj = null;
            JSONArray arr1 = null;
            for (Map<String, Object> m : list) {
                obj = new JSONObject();
                arr1 = new JSONArray();
                arr1.add(m.get("DATE"));
                arr1.add(m.get("counts"));
                obj.put("name", m.get("DATE"));
                obj.put("value", arr1);
                arr.add(obj);
            }
        }
        model.addAttribute("arr", arr.toJSONString());
        model.addAttribute("arrLength", arr.size());
        model.addAttribute("counts", map.get("c"));
        model.addAttribute("start", start);
        model.addAttribute("end", end);

        return "report";
    }

    private Calendar getBeforeDay(Calendar cl) {
        //使用roll方法进行向前回滚
        //cl.roll(Calendar.DATE, -1);
        //使用set方法直接进行设置
        int day = cl.get(Calendar.DATE);
        cl.set(Calendar.DATE, day - 1);
        return cl;
    }


    @PostMapping("/start")
    @ResponseBody
    String start(String wxh) throws IOException {
        Map<String, Object> map = jdbcTemplate.queryForMap(" select * from wx_status where wxh = ? ", new Object[]{
                wxh
        });
        if (null == map || map.size() <= 0) {
            return "fail";
        }
        String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        //先删除图片
        FileSystemUtils.deleteRecursively(new File(path + File.separator + "temp" + File.separator + wxh + File.separator + "qr.png"));
        String cmd = "python " + path + "/newbot.py " + wxh;
        Runtime.getRuntime().exec(cmd);
        return "ok";
    }

}